package util

import com.alibaba.fastjson2.JSONArray
import com.alibaba.fastjson2.parseArray
import entity.Node
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

class FindNode(private val url: String, private val token: String) {
    fun findNodeByName(name: String) {
        runBlocking {
            val responseData = fetchDataFromServer(url)
            val rootNode = responseData?.let { parseNodeListOrChildNodes(it) }
            val node = rootNode?.let { findNodeByName(it, name) }
            if (node != null) {
                println("找到的 node_id：${node.node_id}")
                if (node.child_nodes != null) {
                    println("找到的 child_nodes 数据：")
                    node.child_nodes!!.forEach {
                        println("  node_id: ${it.node_id}, node_name: ${it.node_name}")
                    }
                } else {
                    println("未找到 child_nodes 数据")
                }
            } else {
                println("未找到对应的节点或者数据为空")
            }
        }
    }

    private suspend fun fetchDataFromServer(url: String): JSONArray? = withContext(Dispatchers.IO) {
        val request = Request.Builder()
            .url(url)
            .addHeader("Authorization", "Bearer $token")
            .build()
        val response = OkHttpClient().newCall(request).execute()
        val responseData = response.body.string().parseArray()
        responseData
    }

    private fun parseNodeListOrChildNodes(jsonArray: JSONArray): List<Node> {
        val nodeList = mutableListOf<Node>()
        for (i in 0..<jsonArray.size) {
            val item = jsonArray.getJSONObject(i)
            val node = Node(item)
            node.child_nodes = parseNodeListOrChildNodes(item.getJSONArray("child_nodes"))
            nodeList.add(node)
        }
        return nodeList
    }

    private fun findNodeByName(nodes: List<Node>, nodeName: String): Node? {
        for (node in nodes) {
            if (node.node_name == nodeName) {
                return node
            }
            val childNode = findNodeByName(node.child_nodes ?: emptyList(), nodeName)
            if (childNode != null) {
                return childNode
            }
        }
        return null
    }


    companion object {
        fun parseChildNodes(jsonArray: JSONArray): List<Node> {
            val childNodes = mutableListOf<Node>()
            for (i in 0..<jsonArray.size) {
                val childNode = jsonArray.getJSONObject(i)
                childNodes.add(Node(childNode))
            }
            return childNodes
        }
    }

}
